﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LEDShow.Models;
using LEDShow.Helpers;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Threading;
using System.Threading;
using System.Windows;
using System.Configuration;
using LEDShow.Access;
using System.Data;
using System.Collections;
using XYS.MISS.Photo.PhotoAdmin;
using System.Media;
using System.Windows.Forms;
using System.IO;
using System.Windows.Media;
using System.Net;
using System.Globalization;
using ChineseCalender;

namespace LEDShow.ViewModels
{

    class MainViewModel : ViewModelBase
    {

        private int LineID = -1;

        private int TimeTableID = -1;

        private string TimeTableName = "";

        private string ShowBB_Time = "08:00:00";

        private string ShowYB_Time = "16:20:00";

        private string lastZYSX_Time;

        private string lastAttenWarn_Time;

        private string lastGoal_Time;

        private string lastNoty_Time;

        SqlDataLayer sqlHelper = new SqlDataLayer();

        private SoundPlayer _soundPlayer = null;

        //头像本地路径及网络路径
        private string headImgNativePath;
        private string headImgSourcePath;

        private DataTable cheifDriverOutTimeDt;
        /// <summary>
        /// 0早班，2白班，3夜班
        /// </summary>
        private int CurrentShowClass = -1;

        public ObservableCollection<NamePlateModel> OnDutyDriverList_All = new ObservableCollection<NamePlateModel>();

        public ObservableCollection<NamePlateModel> NextDutyDriverList_All = new ObservableCollection<NamePlateModel>();

        private List<Train> allTrainInfo = new List<Train>();

        private List<string> runningTrain = new List<string>();

        /// <summary>
        /// 更新倒计时线程
        /// </summary>
        public Thread UpdateCountDownThread = null;


        /// <summary>
        /// 更新所有的名牌
        /// </summary>
        public Thread UpdateInfoThread = null;

        ///<summary>
        ///更新头像
        ///</summary>
        public Thread UpdateHeadImageThread = null;

        /// <summary>
        /// 更新车次
        /// </summary>
        public Thread RunningTrainThread = null;

        /// <summary>
        /// 更新通知
        /// </summary>
        public Thread UpdateNotifyThread = null;

        //加载声音
        public Thread LoadSoundThread = null;

        /// <summary>
        /// 更新天气的线程
        /// </summary>
        public Thread UpdateWeatherThread = null;

        private object SynObject = new object();

        private MainView _mainView = null;

        private MainAccess _mainAccess = null;

        /// <summary>
        /// 即将出勤员工列表
        /// </summary>
        private List<string> lstAttendanceRemind = new List<string>();

        /// <summary>
        /// 迟到员工列表
        /// </summary>
        private List<string> lstLateDriver = new List<string>();

        private bool isUpdateAttendance = false;
        private bool isUpdateLateDriver = false;

        //更新头像线程中所使用到的属性
        private double _prosbarValue;
        public double ProsbarValue
        {
            get { return _prosbarValue; }
            set
            {
                _prosbarValue = value;

                OnPropertyChanged("ProsbarValue");
            }
        }

        private int _onDutyTotal;
        public int OnDutyTotal
        {
            get { return _onDutyTotal; }
            set
            {
                _onDutyTotal = value;

                OnPropertyChanged("OnDutyTotal");
            }
        }

        private int _onDutyCurrentPage;
        public int OnDutyCurrentPage
        {
            get { return _onDutyCurrentPage; }
            set
            {
                _onDutyCurrentPage = value;

                OnPropertyChanged("OnDutyCurrentPage");
            }
        }

        private int _nextDutyTotal;
        public int NextDutyTotal
        {
            get { return _nextDutyTotal; }
            set
            {
                _nextDutyTotal = value;

                OnPropertyChanged("NextDutyTotal");
            }
        }

        private int _nextDutyCurrentPage;
        public int NextDutyCurrentPage
        {
            get { return _nextDutyCurrentPage; }
            set
            {
                _nextDutyCurrentPage = value;

                OnPropertyChanged("NextDutyCurrentPage");
            }
        }

        //车场当班人员总页数
        private int _onDutyDriverTotal;
        public int OnDutyDriverTotal
        {
            get { return _onDutyDriverTotal; }
            set
            {
                _onDutyDriverTotal = value;

                OnPropertyChanged("OnDutyDriverTotal");
            }
        }

        //车场当班人员当前页
        private int _onDutyRriverCurrentPage;
        public int OnDutyDriverCurrentPage
        {
            get { return _onDutyRriverCurrentPage; }
            set
            {
                _onDutyRriverCurrentPage = value;

                OnPropertyChanged("OnDutyDriverCurrentPage");
            }
        }

        //车场即将出勤人员总页数
        private int _nextDutyDriverTotal;
        public int NextDutyDriverTotal
        {
            get { return _nextDutyDriverTotal; }
            set
            {
                _nextDutyDriverTotal = value;

                OnPropertyChanged("NextDutyDriverTotal");
            }
        }

        //车场即将出勤人员当前页
        private int _nextDutyRriverCurrentPage;
        public int NextDutyDriverCurrentPage
        {
            get { return _nextDutyRriverCurrentPage; }
            set
            {
                _nextDutyRriverCurrentPage = value;

                OnPropertyChanged("NextDutyDriverCurrentPage");
            }
        }


        private NamePlateModel _onDutyLeader;
        public NamePlateModel OnDutyLeader
        {
            get { return _onDutyLeader; }
            set
            {
                _onDutyLeader = value;
                OnPropertyChanged("OnDutyLeader");
            }
        }

        private NamePlateModel _onDutyPBY;
        public NamePlateModel OnDutyPBY
        {
            get { return _onDutyPBY; }
            set
            {
                _onDutyPBY = value;
                OnPropertyChanged("OnDutyPBY");
            }
        }

        private NamePlateModel _nextLeader;
        public NamePlateModel NextLeader
        {
            get { return _nextLeader; }
            set
            {
                _nextLeader = value;
                OnPropertyChanged("NextLeader");
            }
        }

        private NamePlateModel _nextPBY;
        public NamePlateModel NextPBY
        {
            get { return _nextPBY; }
            set
            {
                _nextPBY = value;
                OnPropertyChanged("NextPBY");
            }
        }

        private NamePlateModel _supervisor1;
        public NamePlateModel Supervisor1
        {
            get { return _supervisor1; }
            set
            {
                _supervisor1 = value;
                OnPropertyChanged("Supervisor1");
            }
        }

        private NamePlateModel _supervisor2;
        public NamePlateModel Supervisor2
        {
            get { return _supervisor2; }
            set
            {
                _supervisor2 = value;
                OnPropertyChanged("Supervisor2");
            }
        }

        private ObservableCollection<Page> _nextDutyPages = new ObservableCollection<Page>();
        public ObservableCollection<Page> NextDutyPages
        {
            get { return _nextDutyPages; }
            set
            {
                _nextDutyPages = value;
            }
        }

        private ObservableCollection<Page> _onDutyPages = new ObservableCollection<Page>();
        public ObservableCollection<Page> OnDutyPages
        {
            get { return _onDutyPages; }
            set
            {
                _onDutyPages = value;
            }
        }

        //车场当班人员页数
        private ObservableCollection<Page> _onDutyDriverPages = new ObservableCollection<Page>();
        public ObservableCollection<Page> OnDutyDriverPages
        {
            get { return _onDutyDriverPages; }
            set
            {
                _onDutyDriverPages = value;
            }
        }

        //车场即将出勤人员页数

        private ObservableCollection<Page> _nextDutyDriverPages = new ObservableCollection<Page>();
        public ObservableCollection<Page> NextDutyDriverPages
        {
            get { return _nextDutyDriverPages; }
            set
            {
                _nextDutyDriverPages = value;
            }
        }

        private ObservableCollection<NamePlateModel> _onDutyDriverList_bind = new ObservableCollection<NamePlateModel>();
        public ObservableCollection<NamePlateModel> OnDutyDriverList_bind
        {
            get { return _onDutyDriverList_bind; }
            set
            {
                _onDutyDriverList_bind = value;

                OnPropertyChanged("OnDutyDriverList_bind");
            }
        }

        private ObservableCollection<NamePlateModel> _nextDutyDriverList_bind = new ObservableCollection<NamePlateModel>();
        public ObservableCollection<NamePlateModel> NextDutyDriverList_bind
        {
            get { return _nextDutyDriverList_bind; }
            set
            {
                _nextDutyDriverList_bind = value;

                OnPropertyChanged("NextDutyDriverList_bind");
            }
        }

        public ObservableCollection<NamePlateModel> OnStationDriverList_All = new ObservableCollection<NamePlateModel>();
        private ObservableCollection<NamePlateModel> _onStationDriverList = new ObservableCollection<NamePlateModel>();
        public ObservableCollection<NamePlateModel> OnStationDriverList
        {
            get { return _onStationDriverList; }
            set
            {
                _onStationDriverList = value;
                OnPropertyChanged("OnStationDriverList");
            }
        }

        public ObservableCollection<NamePlateModel> NextStationDriverList_All = new ObservableCollection<NamePlateModel>();
        private ObservableCollection<NamePlateModel> _nextStationDriverList = new ObservableCollection<NamePlateModel>();
        public ObservableCollection<NamePlateModel> NextStationDriverList
        {
            get { return _nextStationDriverList; }
            set
            {
                _nextStationDriverList = value;
                OnPropertyChanged("NextStationDriverList");
            }
        }



        public MainViewModel(MainView view)
        {
            if (!InitConfigInfo())
            {
                MessageBoxHelper.ShowError("获取配置文件信息失败，请检查配置文件！");
                return;
            }
            this._mainView = view;

            this._mainAccess = new MainAccess(LineID);

            InitSoundThread();

            InitUpdateInfoThread();

            InitRunningTrainThread();

            InitUpdateNotifyThread();

            InitWeatherThread();

            //// 更新头像线程
            InitUpdateHeadImgThread();

            ///更新倒计时线程
            InitCountdownThread();

        }

        /// <summary>
        /// 更新倒计时线程
        /// </summary>
        private void InitCountdownThread()
        {

            if (null == UpdateCountDownThread)
            {
                UpdateCountDownThread = new Thread(new ThreadStart(RefreshCountDown));
                UpdateCountDownThread.SetApartmentState(ApartmentState.STA);
                UpdateCountDownThread.IsBackground = true;
            }

            UpdateCountDownThread.Start();

        }

        public void RefreshCountDown()
        {
            while (true)
            {
                _mainView.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateCountDown(UpdateCountDownDays));
                Thread.Sleep(CONSTDATA.UpdateCountDownSleepTime);
            }
        }
        //更新倒计时
        public delegate void UpdateCountDown();
        public void UpdateCountDownDays()
        {

            DateTime today = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            string sql = "select top 1 nc_nt_date from NotifyContent where nc_nt_id=3 and nc_line=" + Convert.ToInt32(ConfigurationManager.AppSettings["LineID"]) + " order by cast(convert(varchar,nc_date,108) as datetime) desc";
            DataTable dt = sqlHelper.SelectDt(sql);
            DateTime lastDay = new DateTime();
            TimeSpan ts;
            if (dt.Rows.Count > 0)
            {
                lastDay = Convert.ToDateTime(dt.Rows[0][0].ToString());
            }
            ts = lastDay - today;
            
            int subDay = ts.Days;


            if (subDay >= 0)
            {
                _mainView.CountDown.Text = Convert.ToString(subDay);
            }
            else
            {
                _mainView.CountDown.Text = "0";
            }

        }

        //更新头像线程
        private void InitUpdateHeadImgThread()
        {
            if (null == UpdateHeadImageThread)
            {
                UpdateHeadImageThread = new Thread(new ThreadStart(UpdateHeadImage));

                UpdateHeadImageThread.SetApartmentState(ApartmentState.STA);
                UpdateHeadImageThread.IsBackground = true;
            }
            UpdateHeadImageThread.Start();
        }

        private void InitUpdateInfoThread()
        {
            if (null == UpdateInfoThread)
            {
                UpdateInfoThread = new Thread(new ThreadStart(UpdateInfoMethod));

                UpdateInfoThread.SetApartmentState(ApartmentState.STA);
                UpdateInfoThread.IsBackground = true;
            }

            UpdateInfoThread.Start();
        }

        private void InitRunningTrainThread()
        {
            if (null == RunningTrainThread)
            {
                RunningTrainThread = new Thread(new ThreadStart(RefreshRunningTrain));

                RunningTrainThread.SetApartmentState(ApartmentState.STA);
                RunningTrainThread.IsBackground = true;
            }

            RunningTrainThread.Start();
        }

        private void InitUpdateNotifyThread()
        {
            if (null == UpdateNotifyThread)
            {
                UpdateNotifyThread = new Thread(new ThreadStart(RefreshNotify));
                UpdateNotifyThread.SetApartmentState(ApartmentState.STA);
                UpdateNotifyThread.IsBackground = true;
            }

            UpdateNotifyThread.Start();
        }

        /// <summary>
        /// 启动更新天气的线程
        /// </summary>
        private void InitWeatherThread()
        {
            if (CONSTDATA.IsUpdateWeather)
            {
                if (null == UpdateWeatherThread)
                {
                    UpdateWeatherThread = new Thread(new ThreadStart(RefreshWeather));
                    UpdateWeatherThread.SetApartmentState(ApartmentState.STA);
                    UpdateWeatherThread.IsBackground = true;
                }

                UpdateWeatherThread.Start();
            }
        }

        //更新头像
        private void UpdateHeadImage()
        {
            while (true)
            {

                //存储头像的本地路径我网络路径
                headImgNativePath = CONSTDATA.NativePath;
                headImgSourcePath = CONSTDATA.SourcePath;
                //CheckHeadImageNativePath();

                //读取属于同一线路的司机信息
                DataTable dtUserHeadImgInfo = _mainAccess.GetUserHeadImgInfo(Convert.ToString(LineID));

                int error = -1;

                //逐条记录处理
                for (int i = 0; i < dtUserHeadImgInfo.Rows.Count; i++)
                {
                    string user_id = dtUserHeadImgInfo.Rows[i]["user_name"].ToString();                          //司机工号
                    string user_headImgMD5 = dtUserHeadImgInfo.Rows[i]["user_headImgMD5"].ToString();          //最新头像的md5
                    string user_img = dtUserHeadImgInfo.Rows[i]["user_img"].ToString();                        //最新头像的url

                    if (string.IsNullOrEmpty(user_headImgMD5) || string.IsNullOrEmpty(user_img))
                    {
                        continue;
                    }
                    //判断本地是否有该司机头像，没有则从服务器上下载
                    if (!File.Exists(headImgNativePath + user_id + ".jpg"))
                    {
                        //从服务器上面下载头像
                        downloadDriverHeadImg(headImgSourcePath + user_img, user_id, ref error);
                        if (error == 0) //无法连接服务器
                        {
                            MessageBoxHelper.ShowError("更新司机头像信息失败：无法连接远程服务器");
                            break;
                        }

                    }

                    //从服务器下载头像后，再次判断本地是否有该司机头像，没有则设置为默认头像
                    //默认头像使用名为defaultHeadImage.jpg的图片文件
                    if (!File.Exists(headImgNativePath + user_id + ".jpg"))
                    {
                        File.Copy("Images/defaultHeadImage.jpg", headImgNativePath + user_id + ".jpg");

                    }

                    //获取本地头像的md5
                    string nativeMD5 = md5_hash(headImgNativePath + user_id + ".jpg");

                    //比较最新头像的md5和本地头像的md5
                    if (!String.Equals(user_headImgMD5, nativeMD5))
                    {
                        //md5不等，说明头像被更新，下载新头像
                        if (!downloadHeadImg(headImgSourcePath + user_img, user_id, ref error))
                        {
                            if (error == 0) //无法连接服务器
                            {
                                MessageBoxHelper.ShowError("更新司机头像信息失败：无法连接远程服务器");
                                break;
                            }
                        }
                    }

                    ProsbarValue = i * 100 / dtUserHeadImgInfo.Rows.Count;
                }

                File.Delete("temp.jpg");


                Thread.Sleep(CONSTDATA.UpdateHeadImageSleepTime);
            }
        }

        private void UpdateInfoMethod()
        {
            while (true)
            {

                cheifDriverOutTimeDt = sqlHelper.SelectDt(" select bp.* from Tb_BasicPara as bp where bp.line=" + LineID + " and (tag like 'leade%Plan%')");

                int currCls = this.GetCurrentShowClass();
                int nextCls = -1;

                CurrentShowClass = currCls;
                //CurrentShowClass = 0;
                nextCls = this.GetNextShowClass();

                 
                


                //司机长铭牌处理
                DataTable leaderDT = _mainAccess.GetLeaders(CurrentShowClass, nextCls);
                //添加退出勤时间列
                DataTable temp;
                DataTable dt = leaderDT;
                dt.Columns.Add("showPlanAtten", Type.GetType("System.String"));
                dt.Columns.Add("showPlanOutOffTime", Type.GetType("System.String"));
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    SqlDataLayer sql = new SqlDataLayer();
                    string outtag,atttag;

                    switch (Convert.ToInt32(dt.Rows[i]["cls"]))
                    {
                        case 0:
                            outtag = "leaderAMPlanOutOff";
                            atttag = "leaderAMPlanAtten";
                            break;
                        case 2:
                            outtag = "leaderPMPlanOutOff";
                            atttag = "leaderPMPlanAtten";
                            break;
                        case 3:
                            outtag = "leaderNightPlanOutOff";
                            atttag = "leadeNightPlanAtten";
                            break;
                        default:
                            outtag = "leaderNightPlanOutOff";
                            atttag = "leadeNightPlanAtten";
                            break;
                    }

                    //temp = sql.SelectDt("select value from tb_BasicPara where tag='leaderAMPlanOutOff'");
                    DataRow[] rows = cheifDriverOutTimeDt.Select("tag='"+outtag+"'");
                    if (rows.Length > 0)
                    {
                        dt.Rows[i]["showPlanOutOffTime"] = rows[0]["value"].ToString();
                    }

                    rows = cheifDriverOutTimeDt.Select("tag='" + atttag+"'");
                    //temp = sql.SelectDt("select value from tb_BasicPara where tag='leaderPMPlanAtten'");
                    if (rows.Length > 0)
                    {
                        dt.Rows[i]["showPlanAtten"] = rows[0]["value"].ToString();
                    }
                }

                OnDutyLeader = InitLeaderOrPBY(dt, CurrentShowClass);
                NextLeader = InitLeaderOrPBY(dt, nextCls);

                DataTable supervisorDT = _mainAccess.GetSupervisor(CurrentShowClass);
                supervisorDT.Columns.Add("showPlanAtten", Type.GetType("System.String"));
                supervisorDT.Columns.Add("showPlanOutOffTime", Type.GetType("System.String"));
                for (int i = 0; i < supervisorDT.Rows.Count; i++)
                {
                    string outtag, atttag;

                    switch (Convert.ToInt32(supervisorDT.Rows[i]["cls"]))
                    {
                        case 0:
                            outtag = "leaderAMPlanOutOff";
                            atttag = "leaderAMPlanAtten";
                            break;
                        case 2:
                            outtag = "leaderPMPlanOutOff";
                            atttag = "leaderPMPlanAtten";
                            break;
                        case 3:
                            outtag = "leaderNightPlanOutOff";
                            atttag = "leadeNightPlanAtten";
                            break;
                        default:
                            outtag = "leaderNightPlanOutOff";
                            atttag = "leadeNightPlanAtten";
                            break;
                    }

                    //temp = sql.SelectDt("select value from tb_BasicPara where tag='leaderAMPlanOutOff'");
                    DataRow[] rows = cheifDriverOutTimeDt.Select("tag='" + outtag + "'");
                    if (rows.Length > 0)
                    {
                        supervisorDT.Rows[i]["showPlanOutOffTime"] = rows[0]["value"].ToString();
                    }

                    rows = cheifDriverOutTimeDt.Select("tag='" + atttag + "'");
                    //temp = sql.SelectDt("select value from tb_BasicPara where tag='leaderPMPlanAtten'");
                    if (rows.Length > 0)
                    {
                        supervisorDT.Rows[i]["showPlanAtten"] = rows[0]["value"].ToString();
                    }
                }
                DataTable dt1 = supervisorDT.Clone();
                DataTable dt2 = supervisorDT.Clone();
                if (supervisorDT.Rows.Count > 0)
                {
                    dt1.ImportRow(supervisorDT.Rows[0]);
                    Supervisor1 = InitLeaderOrPBY(dt1, CurrentShowClass);
                }
                if (supervisorDT.Rows.Count > 1)
                {
                    dt2.ImportRow(supervisorDT.Rows[1]);
                    Supervisor2 = InitLeaderOrPBY(dt2, CurrentShowClass);
                }

                //派班员铭牌处理
                //DataTable PBYDT = _mainAccess.GetPBYs(CurrentShowClass, nextCls);
                DataTable PBYDT = _mainAccess.GetPBYs();
                string filter_OnDutyPBY = "actualAtten is not null and(" +
                "(outtime is null) or" + //未下班
                    //当前上班时间<计划下班时间
                    // 实际下班时间>当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）
                "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround ) or" +
                    // 实际下班时间>当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点） 当前时间<计划下班时间
                "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（未过十二点） 计划上班时间< 计划下班时间（未过十二点）当前时间<计划下班时间
                "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（未过十二点） 计划上班时间> 计划下班时间（过十二点）
                "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround )  " +
                                                                                  ")";

                DataRow[] resultRows = PBYDT.Select(filter_OnDutyPBY);
                string filter_NextDutyPBY = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") + "' and actualAtten is null ))";
                DataRow[] resultRowsTwo = PBYDT.Select(filter_NextDutyPBY);
                if (resultRows.Count() > 0)
                {
                    OnDutyPBY = InitPBY(PBYDT);
                }
                else
                {
                    //由于一天只有一胩派班员，所以无论是正在出勤还是即将出勤都是同一个人
                    if (resultRowsTwo.Count() > 0)
                    {
                        OnDutyPBY = InitNextPBY(resultRowsTwo);
                    }
                    else
                    {
                        OnDutyPBY = null;
                    }
                }

                //string filter_NextDutyPBY = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") + "' and actualAtten is null ))";
                //DataRow[] resultRowsTwo = PBYDT.Select(filter_NextDutyPBY);
                if (resultRowsTwo.Count() > 0)
                {
                    NextPBY = InitNextPBY(resultRowsTwo);
                }
                //如果没有即将出勤的派班员，则直接设置为正在出勤的派班员
                else
                {
                    if (OnDutyPBY != null)
                    {
                        NextPBY = OnDutyPBY;
                    }
                    else
                    {
                        NextPBY = null;
                    }
                }

                DataTable resultDT = _mainAccess.GetCurrentShowDriver(CurrentShowClass, nextCls);
                _mainView.Dispatcher.Invoke(new DelegateInitRelativeInfo(this.InitRelativeInfo), resultDT, nextCls);
                Thread.Sleep(CONSTDATA.UpdateInfoThreadSleepTime);


            }
        }

        private NamePlateModel InitLeaderOrPBY(DataTable resultDT, int Cls)
        {
            if (null == resultDT || resultDT.Rows.Count < 1 || Cls == -1)
                return null;

            DataRow[] resultRow = null;

            string filter = "cls = " + Cls;

            resultRow = resultDT.Select(filter);
            return GetLeaderOrPBY(resultRow,Cls==CurrentShowClass);

        }

        private NamePlateModel GetLeaderOrPBY(DataRow[] resultRow,bool time)
        {
            if (resultRow == null || resultRow.Length < 1)
                return null;

            NamePlateModel nameModel = new NamePlateModel();
            nameModel.JobNum = resultRow[0]["userID"].ToString();
            nameModel.UserName = resultRow[0]["UserName"].ToString();
            nameModel.Position = resultRow[0]["Position"].ToString();
            //显示退出勤时间
            for (int i = 0; i < resultRow.Count(); i++)
            {
                if (!string.IsNullOrEmpty(resultRow[i]["showPlanOutOffTime"].ToString()) && !string.IsNullOrEmpty(resultRow[i]["showPlanAtten"].ToString()))
                {

                    nameModel.planOutOffTime = Convert.ToDateTime(resultRow[i]["showPlanOutOffTime"].ToString());
                    nameModel.showPlanOutOffTime = Convert.ToDateTime(resultRow[i]["showPlanOutOffTime"].ToString()).ToShortTimeString();
                    nameModel.planAtten = Convert.ToDateTime(resultRow[i]["showPlanAtten"].ToString());
                    nameModel.showPlanAtten = Convert.ToDateTime(resultRow[i]["showPlanAtten"].ToString()).ToShortTimeString();
                    if (time && (nameModel.planOutOffTime.Value.CompareTo(DateTime.Now) < 0 || nameModel.planAtten.Value.CompareTo(DateTime.Now) > 0))
                        return null;
                }
            }

            return nameModel;
        }

        //正在出勤的派班员
        private NamePlateModel InitPBY(DataTable resultDT)
        {
            if (null == resultDT || resultDT.Rows.Count < 1)
                return null;

            string now = DateTime.Now.ToString("HH:mm:ss");
            NamePlateModel nameModel = new NamePlateModel();

            nameModel.JobNum = resultDT.Rows[0]["UserID"].ToString();
            nameModel.UserName = resultDT.Rows[0]["UserName"].ToString();
            nameModel.Position = resultDT.Rows[0]["position"].ToString();
            //显示退出勤时间
            if (!string.IsNullOrEmpty(resultDT.Rows[0]["backGround"].ToString()) && !string.IsNullOrEmpty(resultDT.Rows[0]["planAtten"].ToString()))
            {
                nameModel.planOutOffTime = Convert.ToDateTime(resultDT.Rows[0]["backGround"].ToString());
                nameModel.showPlanOutOffTime = Convert.ToDateTime(resultDT.Rows[0]["backGround"].ToString()).ToShortTimeString();
                nameModel.planAtten = Convert.ToDateTime(resultDT.Rows[0]["planAtten"].ToString());
                nameModel.showPlanAtten = Convert.ToDateTime(resultDT.Rows[0]["planAtten"].ToString()).ToShortTimeString();
            }

            return nameModel;

        }

        //即将出勤的派班员
        private NamePlateModel InitNextPBY(DataRow[] resultRow)
        {
            NamePlateModel nameModel = new NamePlateModel();
            nameModel.JobNum = resultRow[0]["userID"].ToString();
            nameModel.UserName = resultRow[0]["UserName"].ToString();
            nameModel.Position = resultRow[0]["Position"].ToString();
            if (!string.IsNullOrEmpty(resultRow[0]["backGround"].ToString()) && !string.IsNullOrEmpty(resultRow[0]["planAtten"].ToString()))
            {
                nameModel.planOutOffTime = Convert.ToDateTime(resultRow[0]["backGround"].ToString());
                nameModel.showPlanOutOffTime = Convert.ToDateTime(resultRow[0]["backGround"].ToString()).ToShortTimeString();
                nameModel.planAtten = Convert.ToDateTime(resultRow[0]["planAtten"].ToString());
                nameModel.showPlanAtten = Convert.ToDateTime(resultRow[0]["planAtten"].ToString()).ToShortTimeString();
            }

            return nameModel;
        }
        private delegate void DelegateInitRelativeInfo(DataTable DT, int nextCls);
        private void InitRelativeInfo(DataTable DT, int nextCls)
        {
            try
            {

                OnDutyDriverList_All.Clear();
                OnStationDriverList_All.Clear();

                NextDutyDriverList_All.Clear();
                NextStationDriverList_All.Clear();

                if (null == DT || DT.Rows.Count < 1)
                    return;

                DataRow[] rowResults = null;
                //  "cr.attenTime as planAtten, Dgp.dgrp_attendtime as actualAtten, Dgp.dgrp_outtime as outtime ,cr.offTime as backGround" + //add by bin 增加计划发车时间 司机实际出勤时间 司机实际退勤时间 计划退勤时间
                //planAtten 计划上班时间
                //actualAtten 实际出勤时间
                //outtime 实际退勤时间
                //backGround 计划退勤时间

                //string filter_OnDutyDriverList_All = "cls = " + CurrentShowClass + " and type = 5"; //当班正线司机
                // string filter_OnDutyDriverList_All = "actualAtten is not null and ((outtime is null) or (backGround < '"+DateTime.Now+"'))  and type = 5"; //当班正线司机
                //             string filter_OnDutyDriverList_All = @"(type=5 or type=6) and actualAtten is not null and
                //               outtime is null" ;//未下班
                string filter_OnDutyDriverList_All = "(type=5 or type=6) and actualAtten is not null and(" +
                    "(outtime is null) or" + //未下班
                    //当前上班时间<计划下班时间
                    // 实际下班时间>当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）
                    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround ) or" +
                    // 实际下班时间>当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点） 当前时间<计划下班时间
                    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（未过十二点） 计划上班时间< 计划下班时间（未过十二点）当前时间<计划下班时间
                    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（未过十二点） 计划上班时间> 计划下班时间（过十二点）
                    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround )  " +
                                                                                      ")";
                //正线当班人员
                rowResults = DT.Select(filter_OnDutyDriverList_All);
                InitList(OnDutyDriverList_All, rowResults);
                SetNamePlateInfo(OnDutyDriverList_All, SetOutOffException);

                string filter_OnStationDriverList_All = "type<>5 and type<>6  and type<> 7 and actualAtten is not null and(" +
                    "(outtime is null) or" + //未下班
                    //当前上班时间<计划下班时间
                    // 实际下班时间>当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）
                    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround ) or" +
                    // 实际下班时间>当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点） 当前时间<计划下班时间
                    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）当前时间<计划下班时间
                    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点）
                    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround )  " +
                                                                                      ")";

                //NextLeader
                //string nextLeaderFilter = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") +
                //    "' and planAtten>'" + DateTime.Now.AddMinutes(-CONSTDATA.LaterNoRemind).ToString("HH:mm") + "' )) and type = 7 and actualAtten is null ";
                //DataRow[] nextLeaderRows = DT.Select(nextLeaderFilter);
                //if (nextLeaderRows.Length > 0)
                //{
                //    NextLeader = InitNamePlateModel(nextLeaderRows[0]);
                //}
                //else
                //{
                //    NextLeader = null;
                //}

                //OnDutyLeader
                //string onDutyLeaderFilter = "type=7 and actualAtten is not null and(" +
                //    "(outtime is null) or" + //未下班
                //    //当前上班时间<计划下班时间
                //    // 实际下班时间>当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）
                //    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround ) or" +
                //    // 实际下班时间>当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点） 当前时间<计划下班时间
                //    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                //    // 实际下班时间<当前时间（未过十二点） 计划上班时间< 计划下班时间（未过十二点）当前时间<计划下班时间
                //    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                //    // 实际下班时间<当前时间（未过十二点） 计划上班时间> 计划下班时间（过十二点）
                //    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround )  " +
                //                                                                      ")";
                //DataRow[] onDutyLeaderRows = DT.Select(onDutyLeaderFilter);
                //if (onDutyLeaderRows.Length > 0)
                //{
                //    OnDutyLeader = InitNamePlateModel(onDutyLeaderRows[0]);
                //}
                //else
                //{
                //    OnDutyLeader = null;
                //}

                //车场当班人员
                rowResults = DT.Select(filter_OnStationDriverList_All);
                InitList(OnStationDriverList_All, rowResults);


                string filter_OnStationDriverList = "actualAtten is not null and(" +
                    "(outtime is null) or" + //未下班
                    //当前上班时间<计划下班时间
                    // 实际下班时间>当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）
                    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround ) or" +
                    // 实际下班时间>当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点） 当前时间<计划下班时间
                    "(outtime>'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（过十二点） 计划上班时间< 计划下班时间（未过十二点）当前时间<计划下班时间
                    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten<backGround and '" + DateTime.Now.ToString("HH:mm:ss") + "'< backGround) or" +
                    // 实际下班时间<当前时间（过十二点） 计划上班时间> 计划下班时间（过十二点）
                    "(outtime<'" + DateTime.Now.ToString("HH:mm:ss") + "' and  planAtten>backGround )" +
                                                                                      ")";
                //在车场当班人员中增加读派班员，车场调度员等信息
                DataTable resultDT = _mainAccess.GetStationDrivers();
                resultDT.Columns.Add("stringRunTrain", Type.GetType("System.String"));
                resultDT.Columns.Add("reptrain", Type.GetType("System.String"));
                rowResults = resultDT.Select(filter_OnStationDriverList);
                InitList(OnStationDriverList_All, rowResults);

                SetNamePlateInfo(OnStationDriverList_All, SetOutOffException);

                InitPages_OnDuty();
                InitPages_OnDutyDriverPages();
                if (nextCls != -1)
                {
                    //正线即将出勤人员
                    //string filter_NextDutyDriverList_All = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") + "' and actualAtten is null )) and type = 5";
                    rowResults = GetNextDutyDriverListRow(DT);
                    InitList(NextDutyDriverList_All, rowResults);
                    //  SetLateDriver(NextDutyDriverList_All);
                    SetNamePlateInfo(NextDutyDriverList_All, SetLateDriver);

                    //车场即将出勤人员


                    string filter_NextStationDriverList_All =
                        "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm")
                        + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") + "' and planAtten>'" + DateTime.Now.AddMinutes(-CONSTDATA.LaterNoRemind).ToString("HH:mm") + "' )) and actualAtten is null  and type <> 5 and type<>6 and type<> 7";


                    //string filter_NextStationDriverList_All = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm")
                    //    + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") + "' and planAtten>'" + DateTime.Now.AddMinutes(CONSTDATA.LaterNoRemind).ToString("HH:mm") + "' and actualAtten is null )) and type <> 5";

                    rowResults = DT.Select(filter_NextStationDriverList_All);
                    InitList(NextStationDriverList_All, rowResults);

                    string filter_NextStationDriverList = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '"
                        + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") + "' and actualAtten is null) or ( planAtten <'"
                        + DateTime.Now.ToString("HH:mm") + "' and planAtten>'" + DateTime.Now.AddMinutes(-CONSTDATA.LaterNoRemind).ToString("HH:mm") + "' and actualAtten is null ))";
                    rowResults = resultDT.Select(filter_NextStationDriverList);

                    InitList(NextStationDriverList_All, rowResults);

                    SetNamePlateInfo(NextStationDriverList_All, SetLateDriver);
                    InitPages_NextDuty();

                    InitPages_OnDutyDriverPages();
                    InitPages_NextDutyDriverPages();
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex.Message);
            }
        }

        /// <summary>
        /// 获取所有即将上线司机
        /// </summary>
        /// <param name="DT"></param>
        /// <returns></returns>
        private DataRow[] GetNextDutyDriverListRow(DataTable DT)
        {


            string filter_NextDutyDriverList_All = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") + "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") + "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") +
                "' and planAtten>'" + DateTime.Now.AddMinutes(-CONSTDATA.LaterNoRemind).ToString("HH:mm") + "' )) and (type = 5 or type=6) and actualAtten is null ";

            DataRow[] rowResults = DT.Select(filter_NextDutyDriverList_All);
            return rowResults;
        }

        /// <summary>
        /// 获取所有即将上线司机
        /// </summary>
        /// <param name="DT"></param>
        /// <returns></returns>
        private DataRow[] GetNextDutyDriverList(DataTable DT)
        {
            string filter_NextDutyDriverList_All = "((planAtten >  '" + DateTime.Now.ToString("HH:mm") +
                "' and planAtten < '" + DateTime.Now.AddMinutes(CONSTDATA.ShowNextDutyTime).ToString("HH:mm") +
                "') or ( planAtten <'" + DateTime.Now.ToString("HH:mm") + "' and actualAtten is null ))";
            DataRow[] rowResults = DT.Select(filter_NextDutyDriverList_All);
            return rowResults;
        }
        private NamePlateModel InitNamePlateModel(DataRow row)
        {
            NamePlateModel nameModel = new NamePlateModel();
            nameModel.JobNum = row["userID"].ToString();
            nameModel.UserName = row["userName"].ToString();
            nameModel.Position = row["position"].ToString();
            nameModel.RunTrainString = row["stringRunTrain"].ToString();
            if (string.IsNullOrEmpty(row["planAtten"].ToString()))
            {
                nameModel.planAtten = null;
            }
            else
            {
                nameModel.planAtten = Convert.ToDateTime(row["planAtten"].ToString());
                nameModel.showPlanAtten = Convert.ToDateTime(row["planAtten"].ToString()).ToShortTimeString();
            }
            if (string.IsNullOrEmpty(row["backGround"].ToString()))
            {
                nameModel.planOutOffTime = null;
            }
            else
            {
                nameModel.planOutOffTime = Convert.ToDateTime(row["backGround"].ToString());
                nameModel.showPlanOutOffTime = Convert.ToDateTime(row["backGround"].ToString()).ToShortTimeString();
            }
            if (string.IsNullOrEmpty(row["outtime"].ToString()))
            {
                nameModel.actualOutOffTime = null;
            }
            else
            {
                nameModel.actualOutOffTime = Convert.ToDateTime(row["outtime"].ToString());
            }

            if (string.IsNullOrEmpty(row["actualAtten"].ToString()))
            {
                nameModel.actualAtten = null;

                //未出勤设置出勤车次号
                if (!string.IsNullOrEmpty(row["reptrain"].ToString()))
                {
                    string trainNo = row["trainNo"].ToString();
                    if (string.IsNullOrEmpty(trainNo))
                    {

                        string tmp = row["reptrain"].ToString();
                        if (tmp.Length >= 5)
                        {
                            trainNo = tmp.Substring(tmp.Length - 5, 3);
                            nameModel.TrainID = row["reptrain"].ToString() + "-" + trainNo;
                        }
                    }

                    //nameModel.TrainID = rows[i]["reptrain"].ToString();
                }

            }
            else
            {
                nameModel.actualAtten = Convert.ToDateTime(row["actualAtten"].ToString());

                //if (!string.IsNullOrEmpty(rows[i]["reptrain"].ToString()))
                //{
                //    nameModel.TrainID = rows[i]["reptrain"].ToString();
                //}
            }
            return nameModel;
        }
        private void InitList(ObservableCollection<NamePlateModel> theList, DataRow[] rows)
        {
            if (rows == null || rows.Length < 1)
                return;

            for (int i = 0; i < rows.Length; i++)
            {
                //NamePlateModel nameModel = new NamePlateModel();
                //nameModel.JobNum = rows[i]["userID"].ToString();
                //nameModel.UserName = rows[i]["userName"].ToString();
                //nameModel.Position = rows[i]["position"].ToString();
                //nameModel.RunTrainString = rows[i]["stringRunTrain"].ToString();
                //if (string.IsNullOrEmpty(rows[i]["planAtten"].ToString()))
                //{
                //    nameModel.planAtten = null;
                //}
                //else
                //{
                //    nameModel.planAtten = Convert.ToDateTime(rows[i]["planAtten"].ToString());
                //    nameModel.showPlanAtten = Convert.ToDateTime(rows[i]["planAtten"].ToString()).ToShortTimeString();
                //}
                //if (string.IsNullOrEmpty(rows[i]["backGround"].ToString()))
                //{
                //    nameModel.planOutOffTime = null;
                //}
                //else
                //{
                //    nameModel.planOutOffTime = Convert.ToDateTime(rows[i]["backGround"].ToString());
                //    nameModel.showPlanOutOffTime = Convert.ToDateTime(rows[i]["backGround"].ToString()).ToShortTimeString();
                //}
                //if (string.IsNullOrEmpty(rows[i]["outtime"].ToString()))
                //{
                //    nameModel.actualOutOffTime = null;
                //}
                //else
                //{
                //    nameModel.actualOutOffTime = Convert.ToDateTime(rows[i]["outtime"].ToString());
                //}

                //if (string.IsNullOrEmpty(rows[i]["actualAtten"].ToString()))
                //{
                //    nameModel.actualAtten = null;

                //    //未出勤设置出勤车次号
                //    if (!string.IsNullOrEmpty(rows[i]["reptrain"].ToString()))
                //    {
                //        string trainNo = rows[i]["trainNo"].ToString();
                //        if (string.IsNullOrEmpty(trainNo))
                //        {

                //            string tmp = rows[i]["reptrain"].ToString();
                //            if (tmp.Length >= 5) {
                //                trainNo = tmp.Substring(tmp.Length - 5, 3);
                //                nameModel.TrainID = rows[i]["reptrain"].ToString() + "-" + trainNo;
                //            }
                //        }
                        
                //        //nameModel.TrainID = rows[i]["reptrain"].ToString();
                //    }

                //}
                //else
                //{
                //    nameModel.actualAtten = Convert.ToDateTime(rows[i]["actualAtten"].ToString());

                //    //if (!string.IsNullOrEmpty(rows[i]["reptrain"].ToString()))
                //    //{
                //    //    nameModel.TrainID = rows[i]["reptrain"].ToString();
                //    //}
                //}
                NamePlateModel nameModel = InitNamePlateModel(rows[i]);

                theList.Add(nameModel);
            }
        }

        /// <summary>
        /// 设置异常司机的颜色
        /// </summary>
        /// <param name="theList"></param>
        //private void SetLateDriver(ObservableCollection<NamePlateModel> theList)
        //{
        //    foreach (NamePlateModel namePlateModel in theList)
        //    {
        //        if (namePlateModel.planAtten != null && namePlateModel.planAtten < DateTime.Now)
        //        {
        //            namePlateModel.SetLateDriver();
        //        }
        //    }
        //}


        /// <summary>
        /// 设置员工名牌信息
        /// </summary>
        /// <param name="theList"></param>
        private void SetNamePlateInfo(ObservableCollection<NamePlateModel> theList, Action<NamePlateModel> logic)
        {

            foreach (NamePlateModel namePlateModel in theList)
            {
                logic(namePlateModel);
            }
        }

        /// <summary>
        /// 设置迟到司机
        /// </summary>
        /// <param name="namePlateModel"></param>
        private void SetLateDriver(NamePlateModel namePlateModel)
        {
            namePlateModel.status = "正常";
            if (namePlateModel.planAtten != null && namePlateModel.planAtten < DateTime.Now)
            {
                namePlateModel.SetLateDriver();
            }
        }

        /// <summary>
        /// 设置退勤异常
        /// </summary>
        /// <param name="namePlateModel"></param>
        private void SetOutOffException(NamePlateModel namePlateModel)
        {
            #region
            //计划下班时间不为null 并且 计划下班时间<当前时间 8:00 <16:00 晚退
            /*   if (namePlateModel.planOutOffTime != null && namePlateModel.planOutOffTime < DateTime.Now)
               {
                   namePlateModel.SetLeaveEarlierBackGround();
               }
                  //已经退勤 并且快于正常退勤时间 属于早退 (17:00 <18:00)  
               else if (namePlateModel.actualOutOffTime != null  )
               {
                
                
                   if (namePlateModel.planOutOffTime > namePlateModel.planAtten)
                   {
                       //计划退勤时间>计划出勤时间 正常
                       if (namePlateModel.actualOutOffTime < namePlateModel.planOutOffTime)
                       {
                           //实际退勤时间
                           namePlateModel.SetLeaveEarlierBackGround();
                       }
                   }
                   else
                   {
                       //异常情况 （凌晨才下班 例如 计划上班时间为 22:00 计划退勤时间为00:30）
 
                   }
               }*/
            //分一下班和未下班进行比较
            #endregion
            namePlateModel.status = "正常";
            if (namePlateModel.actualOutOffTime == null)
            {
                //未实际下班
                if (DateTime.Now > namePlateModel.planAtten)
                {
                    //当前还是同一天
                    if (namePlateModel.planAtten < namePlateModel.planOutOffTime)
                    {
                        if (DateTime.Now > namePlateModel.planOutOffTime)
                        {
                            namePlateModel.SetOffLateBackGround();
                        }
                    }
                    //else
                    //当前小于计划下班时间 并且未下班，说嘛客车还在跑(正常)
                }
                else if (DateTime.Now < namePlateModel.planAtten)
                {
                    if (DateTime.Now > namePlateModel.actualAtten)
                    {
                        //提前上班 
                        //不用比较
                    }
                    else
                    {
                        //凌晨进行比较
                        if (namePlateModel.planAtten < namePlateModel.planOutOffTime)
                        {
                            //计划上报时间<计划下班时间 同一天 当前已经过凌晨00:00
                            //晚退 
                            namePlateModel.SetOffLateBackGround();
                        }
                        else
                        {
                            //计划上班时间>计划下班时间 （同处于凌晨）
                            if (DateTime.Now > namePlateModel.planOutOffTime)
                            {
                                namePlateModel.SetOffLateBackGround();
                            }
                            //else
                            //当前小于计划下班时间 并且未下班，说嘛客车还在跑(正常)

                        }
                    }
                }

            }
            else
            {
                //已经实际下班
                if (namePlateModel.actualOutOffTime > namePlateModel.planAtten && namePlateModel.planOutOffTime > namePlateModel.planAtten)
                {
                    //实际下班时间>计划上班时间（当天） && 计划下班时间>计划上班时间（当天） 同一天进行比较
                    if (namePlateModel.actualOutOffTime > namePlateModel.planOutOffTime)
                    {
                        //实际下班》计划下班 （晚退）
                        namePlateModel.SetOffLateBackGround();
                    }
                    else
                    {
                        //早退
                        namePlateModel.SetLeaveEarlierBackGround();
                    }
                }
                else
                {
                    if (namePlateModel.actualOutOffTime > namePlateModel.planAtten && namePlateModel.planOutOffTime < namePlateModel.planAtten)
                    {
                        //早退
                        namePlateModel.SetLeaveEarlierBackGround();
                    }
                    else if (namePlateModel.actualOutOffTime < namePlateModel.planAtten && namePlateModel.planOutOffTime > namePlateModel.planAtten)
                    {
                        //晚退
                        namePlateModel.SetOffLateBackGround();
                    }
                    else
                    {
                        //都凌晨 直接比较
                        if (namePlateModel.actualOutOffTime > namePlateModel.planAtten)
                        {
                            //实际下班》计划下班 （晚退）
                            namePlateModel.SetOffLateBackGround();
                        }
                        else
                        {
                            //早退
                            namePlateModel.SetLeaveEarlierBackGround();
                        }

                    }

                }
            }
        }


        private void InitPages_OnDuty()
        {
            //this.OnDutyTotal = OnDutyDriverList_All.Count / CONSTDATA.Number + 1; //总页数
            if (OnDutyDriverList_All.Count != 0 && OnDutyDriverList_All.Count % CONSTDATA.Number == 0)
            {
                this.OnDutyTotal = OnDutyDriverList_All.Count / CONSTDATA.Number; //总页数
            }
            else
            {
                this.OnDutyTotal = OnDutyDriverList_All.Count / CONSTDATA.Number + 1; //总页数
            }
            this.OnDutyPages.Clear();

            for (int i = 1; i <= this.OnDutyTotal; i++)
            {
                int rest = OnDutyDriverList_All.Count - (i - 1) * CONSTDATA.Number;
                int _pageSize = rest >= CONSTDATA.Number ? CONSTDATA.Number : rest;

                this.OnDutyPages.Add(new Page { Name = i.ToString(), PageSize = _pageSize });
            }

            if (OnDutyCurrentPage == 0)
                this.OnDutyCurrentPage = 1; //当前显示页面

            Fun_Pager(1, OnDutyCurrentPage);
        }

        private void InitPages_NextDuty()
        {
            //this.NextDutyTotal = NextDutyDriverList_All.Count / CONSTDATA.Number + 1; //总页数
            if (NextDutyDriverList_All.Count != 0 && NextDutyDriverList_All.Count % CONSTDATA.Number == 0)
            {
                this.NextDutyTotal = NextDutyDriverList_All.Count / CONSTDATA.Number; //总页数
            }
            else
            {
                this.NextDutyTotal = NextDutyDriverList_All.Count / CONSTDATA.Number + 1; //总页数
            }
            this.NextDutyPages.Clear();

            for (int i = 1; i <= this.NextDutyTotal; i++)
            {
                int rest = NextDutyDriverList_All.Count - (i - 1) * CONSTDATA.Number;
                int _pageSize = rest >= CONSTDATA.Number ? CONSTDATA.Number : rest;

                this.NextDutyPages.Add(new Page { Name = i.ToString(), PageSize = _pageSize });
            }
            if (NextDutyCurrentPage == 0)
                this.NextDutyCurrentPage = 1; //当前显示页面

            Fun_Pager(2, NextDutyCurrentPage);
        }

        private void InitPages_OnDutyDriverPages()
        {
            // this.NextDutyTotal = NextDutyDriverList_All.Count / CONSTDATA.Number + 1; //总页数

            if (OnStationDriverList_All.Count != 0 && OnStationDriverList_All.Count % CONSTDATA.DriverNumber == 0)
            {
                this.OnDutyDriverTotal = OnStationDriverList_All.Count / CONSTDATA.DriverNumber;
            }
            else
            {
                this.OnDutyDriverTotal = OnStationDriverList_All.Count / CONSTDATA.DriverNumber + 1;

            }

            // this.NextDutyDriverPages.Clear();
            this.OnDutyDriverPages.Clear();

            for (int i = 1; i <= this.OnDutyDriverTotal; i++)
            {
                int rest = OnStationDriverList_All.Count - (i - 1) * CONSTDATA.DriverNumber;
                int _pageSize = rest >= CONSTDATA.DriverNumber ? CONSTDATA.DriverNumber : rest;

                this.OnDutyDriverPages.Add(new Page { Name = i.ToString(), PageSize = _pageSize });
            }
            if (OnDutyDriverCurrentPage == 0)
                this.OnDutyDriverCurrentPage = 1; //当前显示页面

            Fun_Pager(3, OnDutyDriverCurrentPage);
        }

        /// <summary>
        /// 车场即将出勤人员
        /// </summary>
        private void InitPages_NextDutyDriverPages()
        {
            // this.NextDutyTotal = NextDutyDriverList_All.Count / CONSTDATA.Number + 1; //总页数
            if (NextStationDriverList_All.Count != 0 && NextStationDriverList_All.Count % CONSTDATA.DriverNumber == 0)
            {
                this.NextDutyDriverTotal = NextStationDriverList_All.Count / CONSTDATA.DriverNumber;
            }
            else
            {
                this.NextDutyDriverTotal = NextStationDriverList_All.Count / CONSTDATA.DriverNumber + 1;
            }

            this.NextDutyDriverPages.Clear();

            for (int i = 1; i <= this.NextDutyDriverTotal; i++)
            {
                int rest = NextStationDriverList_All.Count - (i - 1) * CONSTDATA.DriverNumber;
                int _pageSize = rest >= CONSTDATA.DriverNumber ? CONSTDATA.DriverNumber : rest;

                this.NextDutyDriverPages.Add(new Page { Name = i.ToString(), PageSize = _pageSize });
            }
            if (NextDutyDriverCurrentPage == 0)
                this.NextDutyDriverCurrentPage = 1; //当前显示页面

            Fun_Pager(4, NextDutyDriverCurrentPage);
        }



        //private delegate void DelegateFun_Pageer(int thisType,int page);
        /// <summary>
        /// 跳转到相应页，翻页时获取当前的列车信息
        /// </summary>
        /// <param name="thisType">正在出勤的司机，还是即将出勤司机</param>
        public void Fun_Pager(int thisType, int page)
        {
            lock (SynObject)
            {
                string currentTimeStr = DateTime.Now.ToString("HH:mm:ss");

                if (thisType == 1)
                {
                    this.OnDutyDriverList_bind = new ObservableCollection<NamePlateModel>(OnDutyDriverList_All.Take(CONSTDATA.Number * page).Skip(CONSTDATA.Number * (page - 1)));

                    this.OnDutyCurrentPage = page;

                    UpdateDriverList(currentTimeStr);

                }
                else if (thisType == 2)
                {
                    this.NextDutyDriverList_bind = new ObservableCollection<NamePlateModel>(NextDutyDriverList_All.Take(CONSTDATA.Number * page).Skip(CONSTDATA.Number * (page - 1)));

                    this.NextDutyCurrentPage = page;

                    // UpdateDriverList(NextDutyDriverList_bind, currentTimeStr);
                }
                else if (thisType == 3)
                {
                    this.OnStationDriverList = new ObservableCollection<NamePlateModel>(OnStationDriverList_All.Take(CONSTDATA.DriverNumber * page).Skip(CONSTDATA.DriverNumber * (page - 1)));

                    this.OnDutyDriverCurrentPage = page;
                }
                else if (thisType == 4)
                {
                    this.NextStationDriverList = new ObservableCollection<NamePlateModel>(NextStationDriverList_All.Take(CONSTDATA.DriverNumber * page).Skip(CONSTDATA.DriverNumber * (page - 1)));

                    this.NextDutyDriverCurrentPage = page;
                }
            }
        }


        #region 实时更新列车的信息模块

        private void RefreshRunningTrain()
        {
            while (true)
            {
                Thread.Sleep(CONSTDATA.UpdateTrainIDSleepTime);

                InitAllTrainInfo();

                lock (SynObject)
                {
                    string currentTimeStr = DateTime.Now.ToString("HH:mm:ss");
                    int currentTimeInt = GlobalVariables.FormatTimeToInt(currentTimeStr);

                    UpdateRunningTrainList(currentTimeInt);

                    OnDutyCurrentPage = OnDutyCurrentPage + 1 > OnDutyTotal ? 1 : OnDutyCurrentPage + 1;
                    NextDutyCurrentPage = NextDutyCurrentPage + 1 > NextDutyTotal ? 1 : NextDutyCurrentPage + 1;
                    OnDutyDriverCurrentPage = OnDutyDriverCurrentPage + 1 > OnDutyDriverTotal ? 1 : OnDutyDriverCurrentPage + 1;
                    NextDutyDriverCurrentPage = NextDutyDriverCurrentPage + 1 > NextDutyDriverTotal ? 1 : NextDutyDriverCurrentPage + 1;

                    Fun_Pager(1, OnDutyCurrentPage);
                    Fun_Pager(2, NextDutyCurrentPage);
                    
                    Fun_Pager(3, OnDutyDriverCurrentPage);
                    Fun_Pager(4, NextDutyDriverCurrentPage);
                    
                }
            }
        }

        private void InitAllTrainInfo()
        {
            int tempID = -1;
            string tempName = "";

            _mainAccess.CheckHasTimeTableToDate(ref tempID, ref tempName);

            if (tempID != -1 && tempID != TimeTableID)
            {
                TimeTableID = tempID;
                TimeTableName = tempName;

                allTrainInfo.Clear();

                DataTable allTrainDT = _mainAccess.GetAllTrainInfo(TimeTableName, TimeTableID);
                if (null == allTrainDT || allTrainDT.Rows.Count < 1)
                    return;

                for (int i = 0; i < allTrainDT.Rows.Count; i++)
                {
                    Train train = new Train();

                    string trainno = allTrainDT.Rows[i]["TrainNo"].ToString();
                    if (string.IsNullOrEmpty(trainno))
                    {
                        trainno = allTrainDT.Rows[i]["TrainID"].ToString().Substring(0, 3);
                    }
                    train.TrainID = allTrainDT.Rows[i]["TrainID"].ToString() + "-" + trainno;
                    train.BeginTime = Convert.ToInt32(allTrainDT.Rows[i]["TBegin"]);
                    train.TimeAtChangePoint = Convert.ToInt32(allTrainDT.Rows[i]["Arrive"]);
                    train.EndTime = Convert.ToInt32(allTrainDT.Rows[i]["TEnd"]);

                    allTrainInfo.Add(train);
                }

            }
        }

        private void UpdateRunningTrainList(int currentTimeInt)
        {
            runningTrain.Clear();

            if (allTrainInfo.Count < 1)
                return;

            //// runningTrain = (from train in allTrainInfo
            //                 where train.BeginTime <= currentTimeInt && train.EndTime >= currentTimeInt
            //                 select train.TrainID).ToList<string>();
            foreach (Train train in allTrainInfo)
            {
                if (train.BeginTime <= currentTimeInt && train.EndTime >= currentTimeInt)
                {
                    runningTrain.Add(train.TrainID);
                }
            }

        }

        private void UpdateDriverList(ObservableCollection<NamePlateModel> drivers, string currentTimeStr)
        {
            if (null == drivers || drivers.Count < 1)
                return;

            for (int i = 0; i < runningTrain.Count; i++)
            {
                string trainID = runningTrain[i];

                for (int k = 0; k < drivers.Count; k++)
                {
                    if (!string.IsNullOrEmpty(drivers[k].RunTrainString)
                        && drivers[k].RunTrainString.Contains(trainID)
                        // && currentTimeStr.CompareTo(drivers[k].BeginTrainTime) > -1
                        // && currentTimeStr.CompareTo(drivers[k].OffTime) < 1
                        )
                    {
                        //drivers[k].showPlanAtten = "123";
                        drivers[k].TrainID = trainID;
                    }
                    //else
                    //    drivers[k].TrainID = "";
                }
            }
        }

        private void UpdateDriverList(string currentTimeStr)
        {
            if (null == OnDutyDriverList_bind || OnDutyDriverList_bind.Count < 1)
                return;

            for (int i = 0; i < runningTrain.Count; i++)
            {
                string trainID = runningTrain[i];

                for (int k = 0; k < OnDutyDriverList_bind.Count; k++)
                {
                    if (!string.IsNullOrEmpty(OnDutyDriverList_bind[k].RunTrainString)
                        && OnDutyDriverList_bind[k].RunTrainString.Contains(trainID.Substring(0, 5))
                        // && currentTimeStr.CompareTo(drivers[k].BeginTrainTime) > -1
                        // && currentTimeStr.CompareTo(drivers[k].OffTime) < 1
                        )
                    {
                        //drivers[k].showPlanAtten = "123";
                        OnDutyDriverList_bind[k].TrainID = trainID;
                    }

                }
            }
        }

        #endregion

        #region 实时更新各类通知信息模块
        private void RefreshNotify()
        {
            string content = "";
            int level = 0;
            int fontSize = 18;

            while (true)
            {
                string _tempZYSX = _mainAccess.GetLastTime("注意事项");
                string _tempWarn = _mainAccess.GetLastTime("出勤提醒");
                string _tempGoal = _mainAccess.GetLastTime("运营目标");
                string _tempNotify = _mainAccess.GetLastTime("通知");

                if (lastZYSX_Time != _tempZYSX)
                {
                    //更新注意事项
                    //string content = _mainAccess.GetNotifyContent("注意事项");
                    DataTable dt = _mainAccess.GetNotifyContent("注意事项");
                    if (dt.Rows.Count > 0)
                    {
                        content = dt.Rows[0]["nc_xmlcontent"].ToString();
                        level = Convert.ToInt32(dt.Rows[0]["nc_nt_level"].ToString());
                        fontSize = Convert.ToInt32(dt.Rows[0]["nc_nt_fontsize"].ToString());
                    }
                    else
                    {
                        content = "";
                        level = 0;
                        fontSize = 18;
                    }

                    //_mainView.SetContent("注意事项", content);
                    _mainView.Dispatcher.Invoke(new DelegateSetContent(_mainView.SetContent), "注意事项", content, level, fontSize);

                    lastZYSX_Time = _tempZYSX;
                }
                if (true)
                {
                    //更新出勤提醒
                    //先获取数据库的出勤提醒 
                    //string content = _mainAccess.GetNotifyContent("出勤提醒");
                    DataTable dt = _mainAccess.GetNotifyContent("出勤提醒");
                    if (dt.Rows.Count > 0)
                    {
                        content = dt.Rows[0]["nc_content"].ToString();
                        level = Convert.ToInt32(dt.Rows[0]["nc_nt_level"].ToString());
                        fontSize = Convert.ToInt32(dt.Rows[0]["nc_nt_fontsize"].ToString());
                    }
                    else
                    {
                        content = "";
                        level = 0;
                        fontSize = 18;
                    }

                    DataTable dtNextDutyDriver = _mainAccess.GetCurrentShowDriver(0, 0);

                    string lateDriver = GetLateDriver(dtNextDutyDriver);
                    string AttendanceDriver = GetAttendanceDriver(dtNextDutyDriver);
                    if (isUpdateAttendance == true || isUpdateLateDriver == true || _tempWarn != lastAttenWarn_Time)
                    {
                        _mainView.Dispatcher.Invoke(new DelegateSetAttendanceRemind(_mainView.SetAttendanceRemind), content + "\n", lateDriver, AttendanceDriver, level, fontSize);
                        //出勤语音提醒
                        _mainView.Dispatcher.Invoke(new DelegateSpeekAttendanceRemind(_mainView.SpeechAttendanceRemind), content + "\n", lateDriver, AttendanceDriver);

                        isUpdateLateDriver = false;
                        isUpdateAttendance = false;
                    }

                    lastAttenWarn_Time = _tempWarn;
                }
                if (lastGoal_Time != _tempGoal)
                {
                    //更新运营目标
                    //string content = _mainAccess.GetNotifyContent("运营目标");
                    DataTable dt = _mainAccess.GetNotifyContent("运营目标");
                    if (dt.Rows.Count > 0)
                    {
                        content = dt.Rows[0]["nc_content"].ToString();
                        level = Convert.ToInt32(dt.Rows[0]["nc_nt_level"].ToString());
                        fontSize = Convert.ToInt32(dt.Rows[0]["nc_nt_fontsize"].ToString());
                    }
                    else
                    {
                        content = "";
                        level = 0;
                        fontSize = 18;
                    }
                    _mainView.Dispatcher.Invoke(new DelegateSetContent(_mainView.SetContent), "运营目标", content, level, fontSize);

                    lastGoal_Time = _tempGoal;
                }
                if (lastNoty_Time != _tempNotify)
                {
                    DataTable dt_gs = _mainAccess.GetNotifyContent("通知");
                    if (dt_gs.Rows.Count > 0)
                    {
                        content = dt_gs.Rows[0]["nc_content"].ToString();
                        level = Convert.ToInt32(dt_gs.Rows[0]["nc_nt_level"].ToString());
                        fontSize = Convert.ToInt32(dt_gs.Rows[0]["nc_nt_fontsize"].ToString());
                    }
                    else
                    {
                        content = "";
                        level = 0;
                        fontSize = 18;
                    }


                    _mainView.Dispatcher.Invoke(new DelegateSetNotifyContent(_mainView.SetNotifyContent), content, level, fontSize);

                    lastNoty_Time = _tempNotify;
                }

                Thread.Sleep(CONSTDATA.UpdateNotifySleepTime);
            }
        }

        /// <summary>
        /// 获取迟到的司机
        /// </summary>
        /// <returns></returns>
        public string GetLateDriver(DataTable dtDriver)
        {
            List<string> tempLateDriver = new List<string>();
            string lateDriverName = "";
            DataRow[] drs = GetNextDutyDriverListRow(dtDriver);
            foreach (DataRow dr in drs)
            {
                if (!string.IsNullOrEmpty(dr["planAtten"].ToString()) && Convert.ToDateTime(dr["planAtten"].ToString()) < DateTime.Now && Convert.ToDateTime(dr["planAtten"].ToString()).AddMinutes(CONSTDATA.LaterNoRemind) > DateTime.Now)
                {
                    lateDriverName += dr["UserName"].ToString() + " 出勤时间" + dr["planAtten"].ToString() + "\n";
                    //if (!lstLateDriver.Contains(dr["UserName"].ToString()))
                    //{
                    //    isUpdateLateDriver = true;
                    //}
                    tempLateDriver.Add(dr["UserName"].ToString());
                }
            }
            foreach (var lst in lstLateDriver)
            {
                bool isfind = false;
                foreach (var temp in tempLateDriver)
                {
                    if (temp == lst)
                    {
                        isfind = true;
                        break;
                    }
                }
                //如果没有找到
                if (!isfind)
                {
                    isUpdateLateDriver = true;
                    break;
                }
            }
            lstLateDriver.Clear();
            lstLateDriver = tempLateDriver;
            //tempAttendanceRemind.Clear();
            return lateDriverName;
        }

        /// <summary>
        /// 获取即将出勤的时间
        /// </summary>
        /// <returns></returns>
        public string GetAttendanceDriver(DataTable dtDriver)
        {

            string attendanceDriver = "";
            List<string> tempAttendanceRemind = new List<string>();
            DataRow[] drs = GetNextDutyDriverListRow(dtDriver);
            foreach (DataRow dr in drs)
            {
                if (!string.IsNullOrEmpty(dr["planAtten"].ToString()) && Convert.ToDateTime(dr["planAtten"].ToString()) > DateTime.Now && Convert.ToDateTime(dr["planAtten"].ToString()) <= DateTime.Now.AddMinutes(CONSTDATA.AttendanceRemind))
                {
                    attendanceDriver += dr["UserName"].ToString() + " 出勤时间" + dr["planAtten"].ToString() + "\n";
                    //if (!lstAttendanceRemind.Contains(dr["UserName"].ToString()))
                    //{
                    //    _soundPlayer.Play();
                    //    isUpdateAttendance = true;
                    //}
                    tempAttendanceRemind.Add(dr["UserName"].ToString());
                }
            }
            foreach (var lst in lstAttendanceRemind)
            {
                bool isfind = false;
                foreach (var temp in tempAttendanceRemind)
                {
                    if (temp == lst){
                        isfind = true;
                        break;
                    }
                }
                //如果没有找到
                if(!isfind)
                {
                    _soundPlayer.Play();
                    isUpdateAttendance = true;
                    break;
                }
            }
            lstAttendanceRemind.Clear();
            lstAttendanceRemind = tempAttendanceRemind;
            return attendanceDriver;
        }

        /// <summary>
        /// 更新天气
        /// </summary>
        private void RefreshWeather()
        {
            while (true)
            {
                try
                {
                    WeatherWebService getWeather = new WeatherWebService();
                    string[] weatherinfo;
                    weatherinfo = getWeather.getWeatherbyCityName(CONSTDATA.CityName);

                    //string today = weatherinfo[4].Substring(0, weatherinfo[4].IndexOf(' ') + 1);

                    //==============获取第二天的公历农历节日=============
                    DateTime dt = DateTime.Now.AddDays(1);
                    ChineseCalendar cc = new ChineseCalendar(dt);
                    string today = cc.DateString;
                    string traChinDay = cc.ChineseDateString;
                    string theholiday = cc.DateHoliday;
                    string holiday = "";
                    string chineseHoliday = cc.ChineseCalendarHoliday;
                    if (theholiday != "" && chineseHoliday != "")
                    {
                        holiday = holiday + theholiday + " " + chineseHoliday;
                    }
                    else if (theholiday == "" && chineseHoliday != "")
                    {
                        holiday += chineseHoliday;
                    }

                    else if (theholiday != "" && chineseHoliday == "")
                    {
                        holiday += theholiday;
                    }
                    else
                    {
                        holiday = "无";
                    }
                    //=================================================
                    string header = string.Format("{0} {1} {2}", weatherinfo[1], today, traChinDay);
                    //_mainAccess.UpdateWeather(header, holiday, weatherinfo[5], weatherinfo[6].Substring(weatherinfo[6].LastIndexOf(" ") + 1), weatherinfo[7], weatherinfo[10]);
                    _mainAccess.UpdateWeather(header, holiday, weatherinfo[12], weatherinfo[13].Substring(weatherinfo[13].LastIndexOf(" ") + 1), weatherinfo[14], "");
                }
                catch (Exception ex)
                {
                    Helpers.LEDShowGlobalvariables.globalvariables.log.writeError("获取天气信息失败，请检查网络连接。具体信息" + ex.ToString());

                    //_mainAccess.UpdateWeather(CONSTDATA.CityName, "", "", "", "", "");
                }

                Thread.Sleep(CONSTDATA.UpdateWeatherWebSeevicTime);
            }
        }

        //public string ChineseTwentyFourDay()
        //{

        //    DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#

        //    DateTime newDate;

        //    double num;

        //    int y;

        //    string tempStr = "";



        //    y = this._date.Year;



        //    for (int i = 1; i <= 24; i++)
        //    {

        //        num = 525948.76 * (y - 1900) + sTermInfo[i - 1];



        //        newDate = baseDateAndTime.AddMinutes(num);//按分钟计算

        //        if (newDate.DayOfYear == _date.DayOfYear)
        //        {

        //            tempStr = SolarTerm[i - 1];

        //            break;

        //        }

        //    }

        //    return tempStr;



        //}


        private delegate void DelegateSetContent(string type, string content, int level, int fontsize);

        private delegate void DelegateSetNotifyContent(string contents, int levels, int fontsizes);

        private delegate void DelegateSetAttendanceRemind(string content, string later, string driver, int level, int fontsize);

        private delegate void DelegateSpeekAttendanceRemind(string content, string later, string driver);
        #endregion

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <returns></returns>
        private bool InitConfigInfo()
        {
            try
            {
                LineID = Convert.ToInt32(ConfigurationManager.AppSettings["LineID"]);

                CONSTDATA.UpdateTrainIDSleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateTrainIDSleepTime"]) * 1000;

                CONSTDATA.UpdateNotifySleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateNotifySleepTime"]) * 1000;

                CONSTDATA.UpdateWeatherTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateWeatherTime"]) * 1000;

                CONSTDATA.UpdateHeadImageSleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateHeadImageSleepTime"]) * 1000 * 60;

                CONSTDATA.UpdateCountDownSleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateCountDownSleepTime"]) * 1000 * 60;

                CONSTDATA.UpdateInfoThreadSleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateInfoSleepTime"]) * 1000 ;

                CONSTDATA.LaterNoRemind = Convert.ToInt32(ConfigurationManager.AppSettings["LaterNoRemind"]);

                CONSTDATA.AttendanceRemind = Convert.ToInt32(ConfigurationManager.AppSettings["AttendanceRemind"]);

                CONSTDATA.SourcePath = ConfigurationManager.AppSettings["SourcePath"];

                CONSTDATA.NativePath = ConfigurationManager.AppSettings["NativePath"];

                //获取是否更新webservice的配置
                if (ConfigurationManager.AppSettings["UpdateWeather"].ToUpper() == "T")
                {
                    CONSTDATA.IsUpdateWeather = true;
                    CONSTDATA.UpdateWeatherWebSeevicTime = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateWeatherWebSeevicTime"]) * 1000;
                    CONSTDATA.CityName = ConfigurationManager.AppSettings["CityName"];
                }

                CONSTDATA.ShowNextDutyTime = Convert.ToInt32(ConfigurationManager.AppSettings["ShowNextDutyTime"]);



            }
            catch (System.Exception ex)
            {
                Helpers.LEDShowGlobalvariables.globalvariables.log.writeError(ex.ToString());
                return false;

            }
            return true;
        }

        private int GetCurrentShowClass()
        {
            string time = DateTime.Now.ToString("HH:mm:ss");
            int result = -1;

            //if (time.CompareTo(this.ShowBB_Time) <= 0)
            //    result = 0;
            //else if (time.CompareTo(this.ShowYB_Time) <= 0)
            //    result = 2;
            //else
            //    result = 3;

            //string zbAtten =
            DataRow[] rows = cheifDriverOutTimeDt.Select(" (tag = 'leaderAMPlanOutOff' or tag='leaderPMPlanOutOff' or tag='leaderNightPlanOutOff')");
            int countNum = 0;
            for (int i = 0; i < rows.Length; i++)
            {
                if (GlobalVariables.FormatTimeToInt(rows[i]["value"].ToString())>GlobalVariables.FormatTimeToInt(time))
                    countNum++;
            }
            if (countNum > 2)
                result = 0;
            else if (countNum > 1)
                result = 2;
            else if (countNum == 0)
                result = -1;
            else result = 3;

            return result;
        }

        private int GetNextShowClass()
        {
            if (CurrentShowClass == -1)
                return -1;
            else if (CurrentShowClass == 0)
                return 2;
            else if (CurrentShowClass == 2)
                return 3;
            else
                return -1;
        }

        private void InitSoundThread()
        {
            if (null == LoadSoundThread)
            {
                LoadSoundThread = new Thread(new ThreadStart(LoadSound));
                LoadSoundThread.SetApartmentState(ApartmentState.STA);
                LoadSoundThread.IsBackground = true;
            }
            LoadSoundThread.Start();
        }

        /// <summary>
        /// 加载声音
        /// </summary>
        private void LoadSound()
        {
            try
            {
                string soundPath = System.Windows.Forms.Application.StartupPath + @"\Sound\msg.wav";
                if (!File.Exists(soundPath))
                {
                    MessageBoxHelper.ShowError("加载出勤提示音失败！请检查提示音文件是否存在！");
                    return;
                }
                _soundPlayer = new SoundPlayer(soundPath);

            }
            catch (Exception ex)
            {
                Helpers.LEDShowGlobalvariables.globalvariables.log.writeError(ex.ToString());
            }
        }

        //======================================================================================
        // 更新头像部分使用的方法
        //======================================================================================
        /// <summary>
        /// 加载远程图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="user_id"></param>
        /// <param name="err">0:无法连接远程服务器</param>
        /// <returns></returns>
        private bool downloadHeadImg(string url, string user_id, ref int err)
        {
            bool result = true;

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream stream = null;
            FileStream fs = null;
            try
            {
                //下载新头像文件
                request = (HttpWebRequest)WebRequest.Create(url);
                //request.Timeout = 1000;    //1秒超时
                response = (HttpWebResponse)request.GetResponse();
                stream = response.GetResponseStream();
                long sl = response.ContentLength;

                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int count = 0;

                //下载的新头像文件先存储为temp.jpg
                fs = new FileStream("temp.jpg", FileMode.Create);
                while ((count = stream.Read(buffer, 0, bufferSize)) > 0)
                {
                    fs.Write(buffer, 0, count);
                }
                fs.Flush();
                fs.Close();

                //替换掉旧头像
                File.Copy("temp.jpg", headImgNativePath + user_id + ".jpg", true);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ConnectFailure)
                {
                    result = false;

                    err = 0;
                }
            }
            catch (Exception e)
            {

                result = false;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }

                if (fs != null)
                {
                    fs.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
            }

            return result;
        }


        /// <summary>
        /// 下载司机的头像，本地没有司机头像时使用
        /// </summary>
        /// <param name="url"></param>
        /// <param name="user_id"></param>
        /// <param name="err"></param>
        private void downloadDriverHeadImg(string url, string user_id, ref int err)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream stream = null;
            FileStream fs = null;
            try
            {
                //下载新头像文件
                request = (HttpWebRequest)WebRequest.Create(url);
                //request.Timeout = 1000;    //1秒超时
                response = (HttpWebResponse)request.GetResponse();
                stream = response.GetResponseStream();
                long sl = response.ContentLength;

                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int count = 0;

                //下载的头像文件
                fs = new FileStream(headImgNativePath + user_id + ".jpg", FileMode.Create);
                while ((count = stream.Read(buffer, 0, bufferSize)) > 0)
                {
                    fs.Write(buffer, 0, count);
                }
                fs.Flush();
                fs.Close();

            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ConnectFailure)
                {
                    err = 0;
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }

                if (fs != null)
                {
                    fs.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }


        /// <summary>
        /// 生成MD5序列
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string md5_hash(string path)
        {
            string result;
            FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash_byte = get_md5.ComputeHash(get_file);
                result = System.BitConverter.ToString(hash_byte);
                result = result.Replace("-", "");
                get_md5.Clear();
            }
            catch (Exception e)
            {
                result = e.ToString();
            }
            finally
            {
                get_file.Close();
            }

            return result;
        }

        /// <summary>
        /// 获取版本号
        /// </summary>
        /// <returns></returns>
        public string GetVersion()
        {
            return _mainAccess.GetVersion();
        }
    }


}


